package com.ztgf.order.service;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.ztgf.commodity.models.dto.CommodityInfoDTO;
import com.ztgf.commodity.models.service.ICommodityInfoService;
import com.ztgf.common.constant.Result;
import com.ztgf.common.enums.CodeEnum;
import com.ztgf.common.utils.CustomizeUtil;
import com.ztgf.common.utils.DateUtils;
import com.ztgf.common.utils.OrderNumberUtils;
import com.ztgf.dubbo.exception.ServiceException;
import com.ztgf.message.model.bo.MessageAnnouncementSaveBO;
import com.ztgf.message.model.constant.MessageTopicType;
import com.ztgf.message.model.dto.ResponseDTO;
import com.ztgf.message.model.enums.MessageEnum;
import com.ztgf.message.model.service.IKafkaProducerService;
import com.ztgf.order.common.config.YmlConfig;
import com.ztgf.order.mapper.OrderReturnCommodityMapper;
import com.ztgf.order.models.bo.*;
import com.ztgf.order.models.bo.pay.PayOrderSaveBO;
import com.ztgf.order.models.constant.OrderExpireTimeConstant;
import com.ztgf.order.models.dto.*;
import com.ztgf.order.models.dto.purchase.PurchaseCommodityBargainDTO;
import com.ztgf.order.models.service.*;
import com.ztgf.order.models.service.async.IAsyncOrderService;
import com.ztgf.order.models.service.common.ICommonService;
import com.ztgf.order.models.service.purchase.IPurchaseCommodityBargainService;
import com.ztgf.order.models.vo.*;
import com.ztgf.pay.models.bo.PayOrderMotherSaveBO;
import com.ztgf.pay.models.bo.PayOrderRepaySaveBO;
import com.ztgf.pay.models.service.IPayOrderRepayService;
import com.ztgf.pay.models.service.IPayOrderService;
import com.ztgf.shopping.models.service.shop.IShopInfoService;
import com.ztgf.shopping.models.service.shop.IShopQiyuesuoInfoService;
import com.ztgf.shopping.models.vo.shop.ShopInfoVO;
import com.ztgf.sms.models.bo.SmsInfoSaveBO;
import com.ztgf.sms.models.service.ISmsInfoService;
import com.ztgf.sys.models.dto.SysDictDTO;
import com.ztgf.sys.models.service.ISysDictService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionSynchronizationAdapter;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.NumberFormat;
import java.util.*;

import static com.ztgf.common.utils.UtilConstants.*;

/**
 * @author: chenyu.wang
 * @date: 2020-06-30 10:35
 * @Description:
 */
@Slf4j
@DubboService
@Lazy
public class OrderReturnCommodityServiceImpl extends ServiceImpl<OrderReturnCommodityMapper, OrderReturnCommodityDTO> implements IOrderReturnCommodityService {
    @DubboReference
    private IAsyncOrderService asyncOrderService;
    @Resource
    private YmlConfig ymlConfig;
    @Autowired
    private IOrderAfterSaleLogService orderAfterSaleLogService;
    @Autowired
    private IOrderAfterShipService orderAfterShipService;
    @Autowired
    private IOrderCommodityRelationService orderCommodityRelationService;
    @Autowired
    @Lazy
    private IOrderStatusService orderStatusService;
    @DubboReference
    private IKafkaProducerService iKafkaProducerService;
    @Autowired
    @Lazy
    private IOrderInfoService orderInfoService;
    @Autowired
    private IOrderReturnCommodityRefundService orderReturnCommodityRefundService;
    @DubboReference
    private IPayOrderRepayService payOrderRepayService;
    @Autowired
    private IOrderPayRelationService orderPayRelationService;
    @DubboReference
    private IPayOrderService payOrderService;
    @Autowired
    private IOrderReturnExpirationDateService orderReturnExpirationDateService;
    @DubboReference
    private ISysDictService sysDictService;
    @DubboReference
    private ISmsInfoService smsInfoService;
    @DubboReference
    private IShopInfoService shopInfoService;
    @DubboReference
    private IShopQiyuesuoInfoService shopQiyuesuoInfoService;
    @DubboReference
    private ICommodityInfoService commodityInfoService;
    @Autowired
    private IOrderExpirationDateService orderExpirationDateService;

    @Autowired
    private IPurchaseCommodityBargainService purchaseCommodityBargainService;
    @Autowired
    private IOrderPaymentTypeService orderPaymentTypeService;
    @Autowired
    private IOrderPaymentScaleService orderPaymentScaleService;

    @Autowired
    @Lazy
    private ICommonService commonService;

    /**
     * 根据订单id查询 所有售后订单
     *
     * @param orderId
     * @return
     */
    public List<OrderReturnCommodityDTO> selectByOrderId(Long orderId) {
        Wrapper<OrderReturnCommodityDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("order_id", orderId);
        return selectList(wrapper);
    }

    /**
     * @Description: 发起申请退换货
     * @Author: WangChenYu
     * @Param: [saveBO]
     * @Date: 2020-10-09 14:56
     */
    @Transactional
    @Override
    public Result<List<String>> add(OrderReturnCommoditySaveBO saveBO) {

        if(saveBO.getOrderId() == null || saveBO.getSubNumber() == null || saveBO.getSubNumber() <= 0 || saveBO.getOrderCommodityId() == null){
            return new Result<>(CodeEnum.FAIL_100002);
        }

        Result<List<String>> result = new Result<>();
        //判断该订单商品是否已经提交过一次
        Wrapper<OrderReturnCommodityDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("order_commodity_id", saveBO.getOrderCommodityId());
        OrderReturnCommodityDTO selectOne = this.selectOne(wrapper);
        if (null != selectOne) {
            result.setCode(CodeEnum.AFTER_SALE_ORDER_ERROR_320002.getCode());
            result.setMsg(CodeEnum.AFTER_SALE_ORDER_ERROR_320002.getMsg());
            return result;
        }
        OrderReturnCommodityDTO saveDto = new OrderReturnCommodityDTO();
        List<String> date = new ArrayList<>();
        saveDto.setId(ymlConfig.getPkId());
        date.add(saveDto.getId().toString());
        saveDto.setOrderId(saveBO.getOrderId());//订单id
        saveDto.setOrderCommodityId(saveBO.getOrderCommodityId());//订单商品id
        saveDto.setBuyersShopId(saveBO.getBuyersShopId());//买家店铺id
        saveDto.setSellerShopId(saveBO.getSellerShopId());//卖家店铺id
        saveDto.setServiceOrderNumber(OrderNumberUtils.getOrderNumber());//服务单号
        saveDto.setType(saveBO.getType());//退换货类型0申请退货，1申请换货
        if (saveBO.getType() == 0) {
            saveDto.setIsRefund(1);//0不退款，1要退款,退货要退款
            saveDto.setSubNumber(saveBO.getSubNumber());//提交数量
        } else {
            saveDto.setIsRefund(0);//0不退款，1要退款,换货不退款

        }

        saveDto.setReturnReason(saveBO.getReturnReason());//退货原因
        if (StringUtils.isNotBlank(saveBO.getProblemDescription())) {
            saveDto.setProblemDescription(saveBO.getProblemDescription());//问题描述
        }
        if (StringUtils.isNotBlank(saveBO.getCertificateFile())) {
            saveDto.setCertificateFile(saveBO.getCertificateFile());//凭证地址
        }
        if (StringUtils.isNotBlank(saveBO.getContactUser())) {
            saveDto.setContactUser(saveBO.getContactUser());//联系人
        }
        if (StringUtils.isNotBlank(saveBO.getContactPhone())) {
            saveDto.setContactPhone(saveBO.getContactPhone());//联系电话
        }
        if (saveBO.getBuyersAddressId() != null) {
            saveDto.setBuyersAddressId(saveBO.getBuyersAddressId());//买家地址id
        }
        saveDto.setAfterSalesState(1);//售后状态;1申请售后
        saveDto.setAfterSalesAuditState(1);//售后审核状态,1审核中
        saveDto.setInterventionState(0);//平台介入状态;0未介入
        saveDto.setBuyersState(0);//介入买家状态;0未确定
        saveDto.setSellerState(0);//介入卖家状态;0未确定
        saveDto.setShipState(0);//发货状态;0未发货
        saveDto.setIsCancel(0);//是否取消;0未取消
        // 获取订单商品
        OrderCommodityRelationDTO orderCommodityRelationDTO = orderCommodityRelationService.selectById(saveBO.getOrderCommodityId());

        Result rs = saveRefundMoney(saveDto, saveBO.getType(), saveBO.getSubNumber(), saveBO.getReturnMoney(), orderCommodityRelationDTO);
        if(!rs.success()){
            return rs;
        }
        log.info("=========================saveDto"+saveDto);
        boolean insert = this.insert(saveDto);
        if (!insert) {
            result.setCode(CodeEnum.AFTER_SALE_ORDER_ERROR_320000.getCode());
            result.setMsg(CodeEnum.AFTER_SALE_ORDER_ERROR_320000.getMsg());
            result.setData(date);
            return result;
        }
        //修改订单商品是否申请售后
        OrderCommodityRelationDTO orderItem = new OrderCommodityRelationDTO();
        orderItem.setId(saveBO.getOrderCommodityId());
        orderItem.setIsView(1);
        orderCommodityRelationService.updateById(orderItem);
        //保存订单售后日志
        OrderAfterSaleLogDTO logDTO = new OrderAfterSaleLogDTO();
        logDTO.setAfterState(0);//售后状态
        logDTO.setOrderReturnCommodityId(saveDto.getId());//订单售后表id
        logDTO.setCreateUserId(saveDto.getBuyersShopId());//买家店铺id
        logDTO.setProgressContent("您的服务单正在审核，请耐心等待。");
        orderAfterSaleLogService.add(logDTO);
        //发送消息
        this.sendMsg(saveBO.getBuyersShopId(), "发起订单售后", "您的订单已发起售后!", saveDto.getId(), 1);
        //发送短信
        this.sendSms(saveBO.getBuyersShopId(), saveBO.getSellerShopId());
        // 暂停订单待签收倒计时
        this.pauseOrderCountdown(saveBO.getOrderId());
        result.setCode(CodeEnum.SUCCESS.getCode());
        result.setMsg(CodeEnum.SUCCESS.getMsg());
        result.setData(date);
        return result;
    }

    private Result saveRefundMoney(OrderReturnCommodityDTO dto, int type, Integer subNumber, BigDecimal refundMoney, OrderCommodityRelationDTO orderCommodityRelationDTO){
        // 获取订单商品
        OrderInfoDTO orderInfoDTO = orderInfoService.selectById(dto.getOrderId());
        OrderStatusDTO orderStatusDTO = orderStatusService.getByOrderId(dto.getOrderId());
        if(orderInfoDTO == null || orderStatusDTO == null){
            return new Result(CodeEnum.FAIL_100002);
        }
        if(type==2){
            if (refundMoney == null || refundMoney.compareTo(orderCommodityRelationDTO.getActualMoney()) > 0){
                return new Result(CodeEnum.AFTER_SALE_ORDER_ERROR_320007);
            }
            dto.setRefundPrice(refundMoney);
            BigDecimal refundScale = refundMoney.divide(orderCommodityRelationDTO.getActualMoney(),2,BigDecimal.ROUND_DOWN);
            if(orderCommodityRelationDTO.getPurchaseFeeMoneyScalePrice().compareTo(BigDecimal.ZERO) > 0){

                BigDecimal a = (orderCommodityRelationDTO.getPurchaseFeeMoneyScalePrice().multiply(refundScale)).setScale(2,BigDecimal.ROUND_DOWN);
                //退款服务费
                dto.setPurchaseFeeMoneyScaleBackPrice(a);
            }

            //如果是赊销订单 退款佣金

            if(orderInfoDTO.getLastCommissionMoney().compareTo(BigDecimal.ZERO) > 0){
                dto.setRefundCommissionMoney(refundMoney.multiply(orderCommodityRelationDTO.getCommissionRate()).setScale(2,BigDecimal.ROUND_DOWN));
            }
        }else {
            // 商品购买数量
            Integer num = orderCommodityRelationDTO.getNum();

            if (subNumber == null || subNumber > num) {
                return new Result(CodeEnum.AFTER_SALE_ORDER_ERROR_320005);
            }

            BigDecimal refundAmount = orderCommodityRelationDTO.getActualMoney();//默认退款全部
            if(subNumber < num){//部分退款
                //计算折扣
                if(orderCommodityRelationDTO.getDiscountType() == 1){//批发
                    int lastNum = num - subNumber;
                    if(lastNum >= orderCommodityRelationDTO.getWholesaleNum()){//批发价
                        refundAmount = orderCommodityRelationDTO.getActualMoney().divide(BigDecimal.valueOf(num)).multiply(BigDecimal.valueOf(subNumber)).setScale(2, BigDecimal.ROUND_UP);
                    } else {
                        //原价-实付价
                        BigDecimal refundPrice = BigDecimal.ZERO;
                        if(orderCommodityRelationDTO.getPrice().compareTo(orderCommodityRelationDTO.getWholesalePrice()) >= 0){
                            refundPrice = orderCommodityRelationDTO.getPrice();
                        } else {
                            refundPrice = orderCommodityRelationDTO.getWholesalePrice();
                        }
                        //差价
                        BigDecimal differenceMoney = refundPrice.multiply(BigDecimal.valueOf(num - subNumber)).setScale(2);
                        refundAmount = orderCommodityRelationDTO.getActualMoney().subtract(differenceMoney);
                        if(refundAmount.compareTo(BigDecimal.ZERO) < 0){
                            refundAmount = BigDecimal.ZERO;
                        }
                    }
                } else {
                    refundAmount = orderCommodityRelationDTO.getActualMoney().divide(BigDecimal.valueOf(num)).multiply(BigDecimal.valueOf(subNumber)).setScale(2, BigDecimal.ROUND_UP);
                }
            }

            dto.setRefundPrice(refundAmount);

            //计算退款砍价服务费
            if(orderCommodityRelationDTO.getPurchaseFeeMoneyScalePrice().compareTo(BigDecimal.ZERO) > 0){
                //退款服务费
                PurchaseCommodityBargainDTO bargainDTO = purchaseCommodityBargainService.selectById(orderCommodityRelationDTO.getPurchaseCommodityBargainId());
                if(bargainDTO == null){
                    return new Result<>(CodeEnum.FAIL_100002);
                }

                BigDecimal backFeePrice = bargainDTO.getPurchaseFeeMoneyScalePrice().multiply(BigDecimal.valueOf(subNumber)).setScale(2);
                if(backFeePrice.compareTo(orderCommodityRelationDTO.getPurchaseFeeMoneyScalePrice()) > 0){
                    return new Result<>(CodeEnum.FAIL_ORDER_300012);
                }

                dto.setPurchaseFeeMoneyScaleBackPrice(backFeePrice);
            }

            //计算退款佣金
            if(orderInfoDTO.getLastCommissionMoney().compareTo(BigDecimal.ZERO) > 0 && orderStatusDTO.getCommissionMoneyPayStatus() == 2){
                dto.setRefundCommissionMoney(refundAmount.multiply(orderCommodityRelationDTO.getCommissionRate()).setScale(2,BigDecimal.ROUND_DOWN));
                if(dto.getRefundCommissionMoney().compareTo(orderCommodityRelationDTO.getCommissionMoney()) > 0){
                    return new Result<>(CodeEnum.FAIL_200039);
                }
            }
        }

        return new Result();
    }

    /**
     * @Description: 买家取消售后
     * @Author: WangChenYu
     * @Param: [id]
     * @Date: 2020-10-09 14:56
     */
    @Transactional
    @Override
    public Result<List<String>> updateIsCancel(Long id) {
        Result<List<String>> result = new Result<>();
        OrderReturnCommodityDTO dto = this.selectById(id);
        if (null == dto) {
            result.setCode(CodeEnum.AFTER_SALE_ORDER_ERROR_320001.getCode());
            result.setMsg(CodeEnum.AFTER_SALE_ORDER_ERROR_320001.getMsg());
            return result;
        }

        //如果卖家已同意，则无法取消售后
        if (dto.getAfterSalesAuditState() == 2) {
            result.setCode(CodeEnum.AFTER_SALE_ORDER_ERROR_320003.getCode());
            result.setMsg(CodeEnum.AFTER_SALE_ORDER_ERROR_320003.getMsg());
            return result;
        }
        OrderReturnCommodityDTO updateDto = new OrderReturnCommodityDTO();
        updateDto.setId(dto.getId());
        updateDto.setAfterSalesAuditState(4);
        updateDto.setAfterSalesState(3);//售后状态已完成
        updateDto.setIsCancel(1);//取消状态已取消
        boolean flag = this.updateById(updateDto);
        if (!flag) {
            result.setCode(CodeEnum.AFTER_SALE_ORDER_ERROR_320000.getCode());
            result.setMsg(CodeEnum.AFTER_SALE_ORDER_ERROR_320000.getMsg());
            return result;
        } else {
            //售后订单是否全部完成
            Wrapper wrapper = new EntityWrapper();
            wrapper.eq("order_id", dto.getOrderId());
            wrapper.ne("after_sales_state", 3);
            wrapper.eq("is_cancel", 0);
            OrderReturnCommodityDTO returnCommodityDTO = this.selectOne(wrapper);
            if(returnCommodityDTO == null){
                //修改订单过期时间 继续
                OrderExpirationDateDTO expirationDateDTO = new OrderExpirationDateDTO();
                expirationDateDTO.setIsFlag(0);
                wrapper = new EntityWrapper();
                wrapper.eq("order_id", dto.getOrderId());
                wrapper.ne("status", 4);
                orderExpirationDateService.updateById(expirationDateDTO);
            }
        }
        //保存订单售后日志
        OrderAfterSaleLogDTO logDTO = new OrderAfterSaleLogDTO();
        logDTO.setAfterState(1);//售后状态已取消
        logDTO.setOrderReturnCommodityId(dto.getId());//订单售后表id
        logDTO.setCreateUserId(dto.getBuyersShopId());//买家店铺id
        logDTO.setProgressContent("您的服务单已取消。");
        orderAfterSaleLogService.add(logDTO);

        //发送短信
        this.sendSms(dto.getBuyersShopId(), dto.getSellerShopId());
        result.setCode(CodeEnum.SUCCESS.getCode());
        result.setMsg(CodeEnum.SUCCESS.getMsg());
        return result;
    }

    /**
     * @Description: 卖家同意接口
     * @Author: WangChenYu
     * @Param: [id, type:0同意，1不同意]
     * @Date: 2020-10-09 14:56
     */
    @Override
    public Result<List<String>> updateAuditState(Long id, Integer type) {
        Result<List<String>> result = new Result<>();
        OrderReturnCommodityDTO dto = this.selectById(id);
        if (dto == null) {
            result.setCode(CodeEnum.AFTER_SALE_ORDER_ERROR_320001.getCode());
            result.setMsg(CodeEnum.AFTER_SALE_ORDER_ERROR_320001.getMsg());
            return result;
        }
        if (dto.getType()==2){
            //0卖家同意,1卖家不同意
            if (type == ZERO) {
                result = commonService.saveReturnReceive(dto);
            }else{
                boolean noOk = this.updateSellerSayNoOk(dto);
                if (noOk) {
                    result.setCode(CodeEnum.SUCCESS.getCode());
                    result.setMsg(CodeEnum.SUCCESS.getMsg());
                } else {
                    result.setCode(CodeEnum.AFTER_SALE_ORDER_ERROR_320000.getCode());
                    result.setMsg(CodeEnum.AFTER_SALE_ORDER_ERROR_320000.getMsg());
                }
            }

        }else {
            //0卖家同意,1卖家不同意
            if (type == ZERO) {
                boolean isOk = this.updateSellerSayOk(dto);
                if (isOk) {
                    result.setCode(CodeEnum.SUCCESS.getCode());
                    result.setMsg(CodeEnum.SUCCESS.getMsg());
                } else {
                    result.setCode(CodeEnum.AFTER_SALE_ORDER_ERROR_320000.getCode());
                    result.setMsg(CodeEnum.AFTER_SALE_ORDER_ERROR_320000.getMsg());
                }
            } else {
                boolean noOk = this.updateSellerSayNoOk(dto);
                if (noOk) {
                    result.setCode(CodeEnum.SUCCESS.getCode());
                    result.setMsg(CodeEnum.SUCCESS.getMsg());
                } else {
                    result.setCode(CodeEnum.AFTER_SALE_ORDER_ERROR_320000.getCode());
                    result.setMsg(CodeEnum.AFTER_SALE_ORDER_ERROR_320000.getMsg());
                }
            }
        }

        return result;
    }

    /**
     * @Description: 售后申请卖家同意
     * @Author: WangChenYu
     * @Param: [dto]
     * @Date: 2020-10-16 17:31
     */
    @Transactional
    public boolean updateSellerSayOk(OrderReturnCommodityDTO dto) {
        if (dto.getType()==2){
            OrderReturnCommodityDTO updateDto = new OrderReturnCommodityDTO();
            updateDto.setId(dto.getId());
            updateDto.setAfterSalesState(THREE);//3售后完成
            updateDto.setAfterSalesAuditState(TWO);//2卖家同意
            updateDto.setSellerState(ZERO);
            boolean update = this.updateById(updateDto);
            if (!update) {
                return false;
            }
            //查询该订单是否已经完成
            List<OrderReturnCommodityDTO> orderReturnCommodityDTOS = this.selectByOrderId(dto.getOrderId());
            List<OrderReturnCommodityDTO> orderReturnCommodityDTOS1=new ArrayList<>();
            for (OrderReturnCommodityDTO orderReturnCommodityDTO : orderReturnCommodityDTOS) {
                if (orderReturnCommodityDTO.getAfterSalesState()==1 || orderReturnCommodityDTO.getAfterSalesState()==2){
                    orderReturnCommodityDTOS1.add(orderReturnCommodityDTO);
                }
            }
            if (!(orderReturnCommodityDTOS1 !=null && orderReturnCommodityDTOS1.size()>0)) {
                OrderStatusDTO byOrderId = orderStatusService.getByOrderId(dto.getOrderId());
                if (byOrderId!=null){
                    byOrderId.setOrderState(5);
                    orderStatusService.updateById(byOrderId);
                }
            }
        }else {
            OrderReturnCommodityDTO updateDto = new OrderReturnCommodityDTO();
            updateDto.setId(dto.getId());
            updateDto.setAfterSalesState(TWO);//2售后中
            updateDto.setAfterSalesAuditState(TWO);//2卖家同意
            updateDto.setShipState(ONE);//1买家待发货
            updateDto.setSellerState(ZERO);
            boolean update = this.updateById(updateDto);
            if (!update) {
                return false;
            }
            //增加买家发货倒计时
            Date expireTime = this.getExpireTime(OrderExpireTimeConstant.WAIT_DELIVER_GOODS);
            OrderReturnExpirationDateSaveBO expirationDateDTO = new OrderReturnExpirationDateSaveBO();
            expirationDateDTO.setOrderReturnId(dto.getId());//退换货表id
            expirationDateDTO.setStatus(ONE);//买家待发货
            expirationDateDTO.setShopType(ZERO);//买家
            expirationDateDTO.setExpirationTime(expireTime);
            orderReturnExpirationDateService.addCheck(expirationDateDTO);
        }
        //发送消息
        this.sendMsg(dto.getBuyersShopId(), "售后订单审核", "卖家已同意您的售后申请!", dto.getId(), ONE);
        //保存订单售后日志
        OrderAfterSaleLogDTO logDTO = new OrderAfterSaleLogDTO();
        logDTO.setAfterState(TWO);
        logDTO.setOrderReturnCommodityId(dto.getId());//订单售后表id
        logDTO.setCreateUserId(dto.getSellerShopId());//卖家家店铺id
        logDTO.setProgressContent("卖家已同意您的服务申请，请继续下一步操作。");
        orderAfterSaleLogService.add(logDTO);
        //发送短信
        this.sendSms(dto.getBuyersShopId(), dto.getSellerShopId());
        return true;
    }

    /**
     * @Description: 售后申请卖家未同意
     * @Author: WangChenYu
     * @Param: [dto]
     * @Date: 2020-10-16 17:34
     */
    @Transactional
    public boolean updateSellerSayNoOk(OrderReturnCommodityDTO dto) {
        OrderReturnCommodityDTO updateDto = new OrderReturnCommodityDTO();
        updateDto.setId(dto.getId());
        updateDto.setAfterSalesState(TWO);//2售后中
        updateDto.setAfterSalesAuditState(THREE);//3卖家不同意
        updateDto.setSellerState(ZERO);
        boolean update = this.updateById(updateDto);
        if (!update) {
            return false;
        }
        //发送消息
        this.sendMsg(dto.getBuyersShopId(), "售后订单审核", "卖家暂未同意您的售后申请，您可以申请平台介入!", dto.getId(), ONE);
        //保存订单售后日志
        OrderAfterSaleLogDTO logDTO = new OrderAfterSaleLogDTO();
        logDTO.setAfterState(THREE);
        logDTO.setOrderReturnCommodityId(dto.getId());//订单售后表id
        logDTO.setCreateUserId(dto.getSellerShopId());//卖家家店铺id
        logDTO.setProgressContent("卖家未同意您的服务申请，您可以申请平台介入。");
        orderAfterSaleLogService.add(logDTO);
        //发送短信
        this.sendSms(dto.getBuyersShopId(), dto.getSellerShopId());
        return true;
    }

    /**
     * @Description: 卖家给买家发送发货地址，拒绝理由接口
     * @Author: WangChenYu
     * @Param: [updateBO]
     * @Date: 2020-10-09 14:57
     */
    @Transactional
    @Override
    public Result<List<String>> updateSendMeg(OrderReturnCommodityUpdateBO updateBO) {
        Result<List<String>> result = new Result<>();
        OrderReturnCommodityDTO dto = this.selectById(updateBO.getId());
        if (dto == null) {
            result.setCode(CodeEnum.AFTER_SALE_ORDER_ERROR_320001.getCode());
            result.setMsg(CodeEnum.AFTER_SALE_ORDER_ERROR_320001.getMsg());
            return result;
        }
        OrderReturnCommodityDTO updateDto = new OrderReturnCommodityDTO();
        updateDto.setId(dto.getId());
        if (updateBO.getAfterSellerAddress() != null) {
            updateDto.setAfterSellerAddress(updateBO.getAfterSellerAddress());//卖家地址
        }
        if (updateBO.getAfterSellerPhone() != null) {
            updateDto.setAfterSellerPhone(updateBO.getAfterSellerPhone());//卖家联系电话
        }
        if (updateBO.getAfterSellerUser() != null) {
            updateDto.setAfterSellerUser(updateBO.getAfterSellerUser());//卖家联系人
        }
        if (updateBO.getSellerRefuseReason() != null) {
            updateDto.setSellerRefuseReason(updateBO.getSellerRefuseReason());//卖家拒绝理由
        }
        if(updateBO.getAfterSellerAreaId() != null){
            updateDto.setAfterSellerAreaId(updateBO.getAfterSellerAreaId());
        }
        boolean update = this.updateById(updateDto);
        if (!update) {
            result.setCode(CodeEnum.AFTER_SALE_ORDER_ERROR_320000.getCode());
            result.setMsg(CodeEnum.AFTER_SALE_ORDER_ERROR_320000.getMsg());
            return result;
        }
        result.setCode(CodeEnum.SUCCESS.getCode());
        result.setMsg(CodeEnum.SUCCESS.getMsg());
        return result;
    }

    /**
     * 退款买家
     */
    public void refundBuyer(Long orderCommodityId, int lastReturnCommodityNum, Long id) {

        OrderCommodityRelationDTO orderCommodityRelationDTO = orderCommodityRelationService.selectById(orderCommodityId);
        Long orderId = orderCommodityRelationDTO.getOrderId();//订单id
        OrderInfoDTO orderInfoDTO = orderInfoService.selectById(orderId);


        //现货走退款 预售走支付
        OrderPayRelationDTO orderPayRelationDTO = new OrderPayRelationDTO();//业务流水信息
        PayOrderRepaySaveBO payOrderRepaySaveBO = new PayOrderRepaySaveBO();//用作退款接口
        BigDecimal refundMoney = new BigDecimal("0");
        Integer orderPayType = orderInfoDTO.getPayType();
        List<OrderPayRelationDTO> orderPayRelationDTOList = orderPayRelationService.getByOrderId(orderId);


        for (OrderPayRelationDTO tempOrderPayRelationDTO : orderPayRelationDTOList) {
            if (orderPayType == 0) {//现货只取第一条
                orderPayRelationDTO = tempOrderPayRelationDTO;
                break;
            }
            if (orderPayType == 1) {//预售
                orderPayRelationDTO = tempOrderPayRelationDTO;
                break;
            }
        }


        Integer allNum = orderCommodityRelationDTO.getNum();//下单时商品的总数量
        Integer returnCommodityNum = orderCommodityRelationDTO.getReturnCommodityNum();//已经退款的数量
        int lastNum = lastReturnCommodityNum + returnCommodityNum;//这次售后完成的退款数量
        if (lastNum >= allNum) {//最后一次退货
            refundMoney = orderCommodityRelationDTO.getActualMoney().subtract(orderCommodityRelationDTO.getReturnCommodityMoney());
            orderCommodityRelationDTO.setReturnCommodityMoney(orderCommodityRelationDTO.getActualMoney());
            orderCommodityRelationDTO.setReturnCommodityNum(lastNum);
            orderCommodityRelationService.updateById(orderCommodityRelationDTO);
        }
        if (orderCommodityRelationDTO.getDiscountType() == ZERO || orderCommodityRelationDTO.getDiscountType() == TWO) {//不享受优惠和会员

            BigDecimal actualMoney = orderCommodityRelationDTO.getActualMoney();//总实付金额
            BigDecimal currentSingleActualMoney1 = actualMoney.divide(new BigDecimal(allNum), 2, BigDecimal.ROUND_UP);//当前单商品实付
//            if(null != orderCommodityRelationDTO.getPurchaseCommodityType() &&
//                    orderCommodityRelationDTO.getPurchaseCommodityType() == BargainStateEnum.PURCHASE_ORDER_TYPE.getCode()){//询盘商品订单
//                BigDecimal purchaseFeeMoneyScalePrice = orderCommodityRelationDTO.getPurchaseFeeMoneyScalePrice()
//                        .divide(new BigDecimal(allNum), 2, BigDecimal.ROUND_UP);//单个询盘商品对应的服务费
//                currentSingleActualMoney1.add(purchaseFeeMoneyScalePrice);
//            }

            refundMoney = currentSingleActualMoney1.multiply(new BigDecimal(lastReturnCommodityNum));//要退款的金额
            orderCommodityRelationDTO.setReturnCommodityMoney(orderCommodityRelationDTO.getReturnCommodityMoney().add(refundMoney));
            orderCommodityRelationDTO.setReturnCommodityNum(lastNum);
            orderCommodityRelationService.updateById(orderCommodityRelationDTO);
        }

        if (orderCommodityRelationDTO.getDiscountType() == 1) {//批发
            Integer wholesaleNum = orderCommodityRelationDTO.getWholesaleNum();//批发数量
            //这次退款数量后 是否大于等于批发价（退批发价）
            if (allNum - lastNum >= wholesaleNum) {
                refundMoney = orderCommodityRelationDTO.getWholesalePrice().multiply(new BigDecimal(lastReturnCommodityNum));
                orderCommodityRelationDTO.setReturnCommodityMoney(orderCommodityRelationDTO.getReturnCommodityMoney().add(refundMoney));
                orderCommodityRelationDTO.setReturnCommodityNum(lastNum);
                orderCommodityRelationService.updateById(orderCommodityRelationDTO);
            }
            //此次退货后 是否继续享受批发优惠
            if (allNum - returnCommodityNum < wholesaleNum) {//之前已经退款到没有批发价了
                BigDecimal actualMoney = orderCommodityRelationDTO.getActualMoney();//总实付金额
                BigDecimal currentSingleActualMoney1 = actualMoney.divide(new BigDecimal(allNum), 2, BigDecimal.ROUND_UP);//当前单商品实付
//                if(null != orderCommodityRelationDTO.getPurchaseCommodityType() &&
//                        orderCommodityRelationDTO.getPurchaseCommodityType() == BargainStateEnum.PURCHASE_ORDER_TYPE.getCode()){//询盘商品订单
//                    BigDecimal purchaseFeeMoneyScalePrice = orderCommodityRelationDTO.getPurchaseFeeMoneyScalePrice()
//                            .divide(new BigDecimal(allNum), 2, BigDecimal.ROUND_UP);//单个询盘商品对应的服务费
//                    currentSingleActualMoney1.add(purchaseFeeMoneyScalePrice);
//                }
                refundMoney = currentSingleActualMoney1.multiply(new BigDecimal(lastReturnCommodityNum));//要退款的金额
                orderCommodityRelationDTO.setReturnCommodityMoney(orderCommodityRelationDTO.getReturnCommodityMoney().add(refundMoney));
                orderCommodityRelationDTO.setReturnCommodityNum(lastNum);
                orderCommodityRelationService.updateById(orderCommodityRelationDTO);
            } else { //这次退货后已经不享受优惠了 减去之前享受的优惠
                //当前要退货的不算优惠的价格
                BigDecimal money = orderCommodityRelationDTO.getPrice().multiply(new BigDecimal(lastReturnCommodityNum));
                //算出本身的总批发价(不算改价的)
                BigDecimal wholesalePrice = (orderCommodityRelationDTO.getPrice().subtract(orderCommodityRelationDTO.getWholesalePrice())).multiply(new BigDecimal(allNum));
                refundMoney = money.subtract(wholesalePrice).subtract(orderCommodityRelationDTO.getSingleCommodityDiscountChangePrice().multiply(new BigDecimal(lastReturnCommodityNum)));
                orderCommodityRelationDTO.setReturnCommodityMoney(orderCommodityRelationDTO.getReturnCommodityMoney().add(refundMoney));
                orderCommodityRelationDTO.setReturnCommodityNum(lastNum);
                orderCommodityRelationService.updateById(orderCommodityRelationDTO);
            }
        }

        //现货走退款
        if (orderPayType == 0) {
            //创建退款流水记录
            OrderReturnCommodityRefundSaveBO orderReturnCommodityRefundSaveBO = new OrderReturnCommodityRefundSaveBO();
            orderReturnCommodityRefundSaveBO.setOrderId(orderId);
            orderReturnCommodityRefundSaveBO.setPayOrderRepayId(id);
            orderReturnCommodityRefundSaveBO.setRepayMoney(refundMoney);
            orderReturnCommodityRefundSaveBO.setPayType(orderPayRelationDTO.getPayType());
            Long refundId = orderReturnCommodityRefundService.addAndReturnId(orderReturnCommodityRefundSaveBO);

            //其他退款用
            payOrderRepaySaveBO.setPaymentUserId(orderInfoDTO.getBuyShopId());
            payOrderRepaySaveBO.setOriginalOrderId(orderPayRelationDTO.getPayOrderId());
            payOrderRepaySaveBO.setBusinessOrderId(refundId);
            payOrderRepaySaveBO.setMoney(refundMoney);//退款金额
            payOrderRepaySaveBO.setNotifyUrl("1");//订单退款

            if (orderPayRelationDTO.getPayType() == 0) {//余额
                payOrderRepaySaveBO.setUsage("余额-余额退款 订单编号：" + orderInfoDTO.getOrderNo() + " 售后订单id：" + id);
                payOrderRepayService.saveBalanceOrderRepay(payOrderRepaySaveBO);
            }
            if (orderPayRelationDTO.getPayType() == 1) {//网银
                payOrderRepaySaveBO.setUsage("网银-订单退款 订单编号：" + orderInfoDTO.getOrderNo() + " 售后订单id：" + id);
                payOrderRepayService.saveOnlineBankOrderRepay(payOrderRepaySaveBO);
            }
            return;
        } else {
            //处理预售退款，先退冻结的，然后再退首笔款
            //获取第二笔支付金额
            OrderPayRelationDTO twoPayDTO = null;
            for (OrderPayRelationDTO relationDTO : orderPayRelationDTOList) {
                if (orderPayType == 1 && relationDTO.getPeriods() == 2) {
                    twoPayDTO = relationDTO;
                    break;
                }
            }

            BigDecimal freezeMoney = BigDecimal.ZERO; //冻结金额支付
            if (twoPayDTO != null) {//冻结金额
                freezeMoney = twoPayDTO.getRealPayMoney();
            }

            BigDecimal useMoney = BigDecimal.ZERO; //可用余额支付
            if (refundMoney.subtract(freezeMoney).compareTo(BigDecimal.ZERO) > 0) {
                useMoney = refundMoney.subtract(freezeMoney);
            }
            List<OrderPayInfoRelationBO> childOrderList = new ArrayList<>();
            if (useMoney.compareTo(BigDecimal.ZERO) > 0) {
                //创建退款流水记录
                OrderReturnCommodityRefundSaveBO orderReturnCommodityRefundSaveBO = new OrderReturnCommodityRefundSaveBO();
                orderReturnCommodityRefundSaveBO.setOrderId(orderId);
                orderReturnCommodityRefundSaveBO.setPayOrderRepayId(id);
                orderReturnCommodityRefundSaveBO.setRepayMoney(useMoney);
                orderReturnCommodityRefundSaveBO.setPayType(orderPayRelationDTO.getPayType());
                Long refundId = orderReturnCommodityRefundService.addAndReturnId(orderReturnCommodityRefundSaveBO);
                //预售支付子订单用
                OrderPayInfoRelationBO orderPayInfoRelationBO = new OrderPayInfoRelationBO();
                orderPayInfoRelationBO.setPaymentUserId(orderInfoDTO.getSellShopId() + "");
                orderPayInfoRelationBO.setMoney(useMoney);
                orderPayInfoRelationBO.setBusinessOrderNo(orderId + "");//订单id
                orderPayInfoRelationBO.setBusinessOrderWaterNo(refundId + "");
                orderPayInfoRelationBO.setReceiveUserId(orderInfoDTO.getBuyShopId() + "");
                orderPayInfoRelationBO.setMoneyUsage("余额-预售退款 订单编号：" + orderInfoDTO.getOrderNo() + " 售后订单id：" + id);
                orderPayInfoRelationBO.setTrsFlag("A00");
                childOrderList.add(orderPayInfoRelationBO);

                //创建退款流水记录
                OrderReturnCommodityRefundSaveBO orderReturnCommodityRefundSaveBO1 = new OrderReturnCommodityRefundSaveBO();
                orderReturnCommodityRefundSaveBO1.setOrderId(orderId);
                orderReturnCommodityRefundSaveBO1.setPayOrderRepayId(id);
                orderReturnCommodityRefundSaveBO1.setRepayMoney(freezeMoney);
                orderReturnCommodityRefundSaveBO1.setPayType(orderPayRelationDTO.getPayType());
                refundId = orderReturnCommodityRefundService.addAndReturnId(orderReturnCommodityRefundSaveBO1);
                //预售支付子订单用
                OrderPayInfoRelationBO orderPayInfoRelationBO1 = new OrderPayInfoRelationBO();
                orderPayInfoRelationBO1.setPaymentUserId(orderInfoDTO.getSellShopId() + "");
                orderPayInfoRelationBO1.setMoney(freezeMoney);
                orderPayInfoRelationBO1.setBusinessOrderNo(orderId + "");//订单id
                orderPayInfoRelationBO1.setBusinessOrderWaterNo(refundId + "");
                orderPayInfoRelationBO1.setReceiveUserId(orderInfoDTO.getBuyShopId() + "");
                orderPayInfoRelationBO1.setMoneyUsage("余额-预售退款 订单编号：" + orderInfoDTO.getOrderNo() + " 售后订单id：" + id);
                orderPayInfoRelationBO1.setTrsFlag("B01");
                childOrderList.add(orderPayInfoRelationBO1);
            }

            String s = JSON.toJSONString(childOrderList);

            PayOrderMotherSaveBO payOrderMotherSaveBO = new PayOrderMotherSaveBO();//用作支付接口(预售退款)
            //预售用
            payOrderMotherSaveBO.setPaymentUserId(orderInfoDTO.getSellShopId());
            payOrderMotherSaveBO.setMoney(refundMoney);
            payOrderMotherSaveBO.setTrsFlag("B01");
//            payOrderMotherSaveBO.setPayType(4);
            payOrderMotherSaveBO.setChildOrderList(s);

            //预售走支付
            payOrderService.saveBalancePay(payOrderMotherSaveBO);
        }


    }

    @Transactional(rollbackFor = ServiceException.class)
    public void saveReceive(OrderReturnCommodityDTO dto){
        //修改售后订单状态
        OrderReturnCommodityDTO newDTO = new OrderReturnCommodityDTO();
        newDTO.setId(dto.getId());
        newDTO.setAfterSalesState(3);//3售后完成

        if (dto.getType()==2){
            newDTO.setAfterSalesAuditState(2);//2卖家同意
            newDTO.setSellerState(ZERO);
        } else {
            newDTO.setShipState(6);
        }
        //6卖家已签收
        newDTO.setIsRefund(1);//1退款
        Wrapper wrapper = new EntityWrapper();
        wrapper.eq("id", dto.getId());
        wrapper.ne("after_sales_state", 3);
        boolean flag = this.update(newDTO, wrapper);
        if (!flag) {
            throw new ServiceException(CodeEnum.FAIL_100008);
        }
        //修改商品退款数量及金额
        OrderCommodityRelationDTO orderCommodityRelationDTO = orderCommodityRelationService.selectById(dto.getOrderCommodityId());
        OrderCommodityRelationDTO newOrderCommodityRelationDTO = new OrderCommodityRelationDTO();
        newOrderCommodityRelationDTO.setId(orderCommodityRelationDTO.getId());
        newOrderCommodityRelationDTO.setReturnCommodityNum(dto.getSubNumber());
        newOrderCommodityRelationDTO.setReturnCommodityMoney(dto.getRefundPrice());
        newOrderCommodityRelationDTO.setPurchaseFeeMoneyScaleBackPrice(dto.getPurchaseFeeMoneyScaleBackPrice());
        wrapper = new EntityWrapper();
        wrapper.eq("id", orderCommodityRelationDTO.getId());
        wrapper.eq("return_commodity_num", orderCommodityRelationDTO.getReturnCommodityNum());
        wrapper.eq("return_commodity_money", orderCommodityRelationDTO.getReturnCommodityMoney());
        flag = orderCommodityRelationService.update(newOrderCommodityRelationDTO, wrapper);
        if (!flag) {
            throw new ServiceException(CodeEnum.FAIL_100008);
        }



        //保存订单售后日志
        OrderAfterSaleLogDTO logDTO = new OrderAfterSaleLogDTO();
        logDTO.setAfterState(4);
        logDTO.setOrderReturnCommodityId(dto.getId());//订单售后表id
        logDTO.setCreateUserId(dto.getSellerShopId());//卖家家店铺id
        logDTO.setProgressContent("卖家已签收，服务完成，请等待退款。");
        flag = orderAfterSaleLogService.add(logDTO);
        if (!flag) {
            throw new ServiceException(CodeEnum.FAIL_100008);
        }
        //设置退款金额
        saveRefundPay(dto);
        //发送消息
        this.sendMsg(dto.getBuyersShopId(), "售后订单签收", "卖家已签收，请等待退款!", dto.getId(), 1);
        //发送短信
        this.sendSms(dto.getBuyersShopId(), dto.getSellerShopId());
        TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
            @Override
            public void afterCommit() {
                log.error("---退款签收 退款金额------>");
                PayOrderSaveBO bo = new PayOrderSaveBO();
                bo.setType(7);
                bo.setIds(dto.getId().toString());
                bo.setPayType(0);
                asyncOrderService.savePay(bo, false);
            }
        });

        OrderPaymentTypeDTO orderPaymentTypeDTO = orderPaymentTypeService.getOrderPaymentByOrderIdAndType(dto.getOrderId(),1,2);
        if(orderPaymentTypeDTO == null) {
            TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
                @Override
                public void afterCommit() {
                    log.error("---退款佣金------>");
                    PayOrderSaveBO bo = new PayOrderSaveBO();
                    bo.setType(19);
                    bo.setIds(dto.getId().toString());
                    bo.setPayType(0);
                    asyncOrderService.savePay(bo, false);
                }
            });
        }
    }

    /**
     * 设置退款金额
     * @param orderReturnCommodityDTO
     */
    private void saveRefundPay(OrderReturnCommodityDTO orderReturnCommodityDTO){

        if(orderReturnCommodityDTO.getRefundPrice().compareTo(BigDecimal.ZERO) > 0){

            OrderInfoDTO orderInfoDTO = orderInfoService.selectById(orderReturnCommodityDTO.getOrderId());
            if(orderInfoDTO == null){
                log.error("售后订单退款saveAfterSalePayBack orderInfoDTO is null--->>>"  + JSON.toJSONString(orderReturnCommodityDTO));
                throw new ServiceException(CodeEnum.FAIL_100002);
            }

//            //修改退款的佣金
//            if(orderReturnCommodityDTO.getRefundCommissionMoney().compareTo(BigDecimal.ZERO) > 0){
//                OrderInfoDTO newOrderInfo = new OrderInfoDTO();
//                newOrderInfo.setRefundCommissionMoney(orderReturnCommodityDTO.getRefundCommissionMoney().add(orderInfoDTO.getRefundCommissionMoney()));
//                newOrderInfo.setLastCommissionMoney(orderInfoDTO.getLastCommissionMoney().subtract(orderReturnCommodityDTO.getRefundCommissionMoney()));
//                newOrderInfo.setId(orderInfoDTO.getId());
//                Wrapper wrapper = new EntityWrapper<>();
//                wrapper.eq("id", orderInfoDTO.getId());
//                wrapper.eq("refund_commission_money", orderInfoDTO.getRefundCommissionMoney());
//                wrapper.eq("last_commission_money", orderInfoDTO.getLastCommissionMoney());
//                if(!orderInfoService.update(newOrderInfo, wrapper)){
//                    throw new ServiceException(CodeEnum.FAIL_100077);
//                }
//            }

            OrderPaymentTypeDTO typeDTO = orderPaymentTypeService.getOrderPaymentByOrderIdAndType(orderInfoDTO.getId(), 1,2);
            if(typeDTO != null){//赊销订单
                //获取支付列表
                Wrapper wrapper = new EntityWrapper<>();
                wrapper.eq("order_id", orderInfoDTO.getId());
                wrapper.orderBy("periods", false);
                List<OrderPayRelationDTO> orderPayRelationDTOList = orderPayRelationService.selectList(wrapper);
                if(orderPayRelationDTOList == null || orderPayRelationDTOList.size() == 0){
                    log.error("售后订单退款saveAfterSalePayBack  orderPayRelationDTOListis null--->>>"  + JSON.toJSONString(orderReturnCommodityDTO));
                    throw new ServiceException(CodeEnum.FAIL_100002);
                }

                BigDecimal refundMoney = orderReturnCommodityDTO.getRefundPrice();//应退金额
                BigDecimal realRefundMoney = BigDecimal.ZERO;
                for(OrderPayRelationDTO orderPayRelationDTO : orderPayRelationDTOList){
                    if(refundMoney.compareTo(BigDecimal.ZERO) <= 0){
                        continue;
                    }
                    if(orderPayRelationDTO.getPayState() == 2){
                        BigDecimal unRefoundMoney = orderPayRelationDTO.getRealPayMoney().subtract(orderPayRelationDTO.getRefundMoney());//未退完金额

                        if(unRefoundMoney.compareTo(BigDecimal.ZERO) > 0){ //未退完
                            if(unRefoundMoney.compareTo(refundMoney) >= 0){//满足退款
                                if(!(orderPayRelationDTO.getPayType() != null && orderPayRelationDTO.getPayType() == 2)) {
                                    realRefundMoney = realRefundMoney.add(refundMoney);
                                }
                                savePayRefund(orderInfoDTO, orderPayRelationDTO, orderReturnCommodityDTO, refundMoney, 1, false, false, true);
                                break;
                            } else {//不满足退款
                                if(!(orderPayRelationDTO.getPayType() != null && orderPayRelationDTO.getPayType() == 2)) {
                                    realRefundMoney = realRefundMoney.add(unRefoundMoney);
                                }
                                refundMoney = refundMoney.subtract(unRefoundMoney);
                                savePayRefund(orderInfoDTO, orderPayRelationDTO, orderReturnCommodityDTO, unRefoundMoney, 1, false, false, true);
                            }
                        } else {//已退完
                            continue;
                        }
                    } else if(orderPayRelationDTO.getPayState() == 4){//取消支付订单
                        continue;
                    } else {//未支付订单
                        BigDecimal unRefoundMoney = orderPayRelationDTO.getRealPayMoney().subtract(orderPayRelationDTO.getRefundMoney());//未退完金额
                        if(refundMoney.compareTo(unRefoundMoney) > 0){//修改取消
                            refundMoney = refundMoney.subtract(unRefoundMoney);
                            updateCencalPay(orderPayRelationDTO, unRefoundMoney, true);
                        } else if(refundMoney.compareTo(unRefoundMoney) == 0){
                            updateCencalPay(orderPayRelationDTO, unRefoundMoney, true);
                            break;
                        } else {//修改待支付金额
                            updateUnrefundMoney(orderPayRelationDTO, refundMoney, true);
                            break;
                        }
                    }
                }

                if(realRefundMoney.compareTo(BigDecimal.ZERO) > 0){
                    //添加日志
                    OrderReturnCommodityRefundSaveBO refundSaveBO = new OrderReturnCommodityRefundSaveBO();
                    refundSaveBO.setOrderId(orderInfoDTO.getId());
                    refundSaveBO.setRefundOrderId(orderReturnCommodityDTO.getId());
                    refundSaveBO.setPayType(0);
                    refundSaveBO.setMoneyType(1);
                    refundSaveBO.setRepayMoney(realRefundMoney);
                    refundSaveBO.setPayUserId(orderInfoDTO.getSellShopId());
                    refundSaveBO.setRecvUserId(orderInfoDTO.getBuyShopId());
                    orderReturnCommodityRefundService.add(refundSaveBO);
                } else {
                    //修改退款完成状态
                    updateRefundFinish(orderReturnCommodityDTO);
                }
//                //判断是否已支付完成
//                TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
//                    @Override
//                    public void afterCommit() {
//                        //修改订单支付完成状态
//                        orderPaymentTypeService.updatePayStatus(orderReturnCommodityDTO.getOrderId(), null);
//                    }
//                });
                return;
            }

            //获取支付列表
            Wrapper wrapper = new EntityWrapper<>();
            wrapper.eq("order_id", orderInfoDTO.getId());
            wrapper.orderBy("periods", true);
            List<OrderPayRelationDTO> orderPayRelationDTOList = orderPayRelationService.selectList(wrapper);
            if(orderPayRelationDTOList == null || orderPayRelationDTOList.size() == 0){
                log.error("售后订单退款saveAfterSalePayBack  orderPayRelationDTOListis null--->>>"  + JSON.toJSONString(orderReturnCommodityDTO));
                throw new ServiceException(CodeEnum.FAIL_100002);
            }

            if(orderInfoDTO.getPayType() == 0){//全款
                OrderPayRelationDTO orderPayRelationDTO = orderPayRelationDTOList.get(0);
                savePayRefund(orderInfoDTO, orderPayRelationDTO, orderReturnCommodityDTO, orderReturnCommodityDTO.getRefundPrice(), 0, true, true);
            } else {
                OrderPayRelationDTO orderPayRelationDTO = orderPayRelationDTOList.get(1);//第二次支付退款金额

                BigDecimal unRefoundMoney = orderPayRelationDTO.getRealPayMoney().subtract(orderPayRelationDTO.getRefundMoney());//未退完金额
                BigDecimal refundMoney = orderReturnCommodityDTO.getRefundPrice();//退款金额

                if(unRefoundMoney.compareTo(BigDecimal.ZERO) > 0){ //未退完
                    if(unRefoundMoney.compareTo(orderReturnCommodityDTO.getRefundPrice()) >= 0){//第二次满足退款
                        savePayRefund(orderInfoDTO, orderPayRelationDTO, orderReturnCommodityDTO, refundMoney, 0, true, true);
                    } else {//分两次退款
                        boolean updateRefundFinish = true;
                        if(orderPayRelationDTO.getPayType() != null && orderPayRelationDTO.getPayType() == 2){
                            //票据支付不退
                        } else {//退款
                            OrderReturnCommodityRefundSaveBO refundSaveBO = new OrderReturnCommodityRefundSaveBO();
                            refundSaveBO.setOrderId(orderInfoDTO.getId());
                            refundSaveBO.setPayOrderRepayId(orderPayRelationDTO.getId());
                            refundSaveBO.setRefundOrderId(orderReturnCommodityDTO.getId());
                            refundSaveBO.setPayType(0);
                            refundSaveBO.setMoneyType(0);
                            refundSaveBO.setRepayMoney(unRefoundMoney);
                            refundSaveBO.setPayUserId(orderInfoDTO.getSellShopId());
                            refundSaveBO.setRecvUserId(orderInfoDTO.getBuyShopId());
                            orderReturnCommodityRefundService.add(refundSaveBO);
                            updateRefundFinish = false;
                        }
                        //修改未退完金额
                        updateUnrefundMoney(orderPayRelationDTO, unRefoundMoney);
                        orderPayRelationDTO = orderPayRelationDTOList.get(0);//第二次支付退款金额
                        if(orderPayRelationDTO.getPayType() != null && orderPayRelationDTO.getPayType() == 2){
                            //票据支付不退
                        } else {//退款
                            OrderReturnCommodityRefundSaveBO refundSaveBO = new OrderReturnCommodityRefundSaveBO();
                            refundSaveBO.setOrderId(orderInfoDTO.getId());
                            refundSaveBO.setPayOrderRepayId(orderPayRelationDTO.getId());
                            refundSaveBO.setRefundOrderId(orderReturnCommodityDTO.getId());
                            refundSaveBO.setPayType(0);
                            refundSaveBO.setMoneyType(1);
                            refundSaveBO.setRepayMoney(refundMoney.subtract(unRefoundMoney));
                            refundSaveBO.setPayUserId(orderInfoDTO.getSellShopId());
                            refundSaveBO.setRecvUserId(orderInfoDTO.getBuyShopId());
                            orderReturnCommodityRefundService.add(refundSaveBO);
                            updateRefundFinish = false;
                        }
                        //修改未退完金额
                        updateUnrefundMoney(orderPayRelationDTO, refundMoney.subtract(unRefoundMoney));
                        if(updateRefundFinish){
                            updateRefundFinish(orderReturnCommodityDTO);
                        }
                    }
                } else {//已退完
                    orderPayRelationDTO = orderPayRelationDTOList.get(0);
                    savePayRefund(orderInfoDTO, orderPayRelationDTO, orderReturnCommodityDTO, refundMoney, 1, true, true);
                }

            }
        }
    }

    private void savePayRefund(OrderInfoDTO orderInfoDTO, OrderPayRelationDTO orderPayRelationDTO, OrderReturnCommodityDTO orderReturnCommodityDTO, BigDecimal refundMoney, int moneyType, boolean updateRefundFinish, boolean addRefund){
        this.savePayRefund(orderInfoDTO, orderPayRelationDTO, orderReturnCommodityDTO, refundMoney, moneyType, updateRefundFinish, addRefund, false);
    }

    /**
     * 保存退款业务
     * @param orderInfoDTO
     * @param orderPayRelationDTO
     * @param orderReturnCommodityDTO
     * @param moneyType
     */
    private void savePayRefund(OrderInfoDTO orderInfoDTO, OrderPayRelationDTO orderPayRelationDTO, OrderReturnCommodityDTO orderReturnCommodityDTO, BigDecimal refundMoney, int moneyType, boolean updateRefundFinish, boolean addRefund, boolean isSxOrder){
        if(orderPayRelationDTO.getPayType() != null && orderPayRelationDTO.getPayType() == 2){
            log.error("售后订单退款 票据支付 不用退款--->>>"  + JSON.toJSONString(orderReturnCommodityDTO));
            if(updateRefundFinish){
                updateRefundFinish(orderReturnCommodityDTO);
            }

            //修改未退完金额
            updateUnrefundMoney(orderPayRelationDTO, refundMoney, isSxOrder);
            return;
        }

        if(addRefund){
            OrderReturnCommodityRefundSaveBO refundSaveBO = new OrderReturnCommodityRefundSaveBO();
            refundSaveBO.setOrderId(orderInfoDTO.getId());
            refundSaveBO.setPayOrderRepayId(orderPayRelationDTO.getId());
            refundSaveBO.setRefundOrderId(orderReturnCommodityDTO.getId());
            refundSaveBO.setPayType(0);
            refundSaveBO.setMoneyType(moneyType);
            refundSaveBO.setRepayMoney(refundMoney);
            refundSaveBO.setPayUserId(orderInfoDTO.getSellShopId());
            refundSaveBO.setRecvUserId(orderInfoDTO.getBuyShopId());
            orderReturnCommodityRefundService.add(refundSaveBO);
        }
        //修改未退完金额
        updateUnrefundMoney(orderPayRelationDTO, refundMoney, isSxOrder);
    }

    private void updateUnrefundMoney(OrderPayRelationDTO orderPayRelationDTO, BigDecimal refundMoney){
        this.updateUnrefundMoney(orderPayRelationDTO, refundMoney, false);
    }
    /**
     * 修改未退完金额
     * @param orderPayRelationDTO
     * @param refundMoney
     */
    private void updateUnrefundMoney(OrderPayRelationDTO orderPayRelationDTO, BigDecimal refundMoney, boolean isSxOrder){
        //修改未退完金额
        OrderPayRelationDTO newOrderPayRelationDTO = new OrderPayRelationDTO();
        newOrderPayRelationDTO.setRefundMoney(orderPayRelationDTO.getRefundMoney().add(refundMoney));
        Wrapper wrapper = new EntityWrapper<>();
        wrapper.eq("id", orderPayRelationDTO.getId());
        wrapper.and("real_pay_money >= {0} and {1} >= 0", newOrderPayRelationDTO.getRefundMoney(), newOrderPayRelationDTO.getRefundMoney());
        boolean flag = orderPayRelationService.update(newOrderPayRelationDTO, wrapper);
        if(!flag){
            throw new ServiceException(CodeEnum.FAIL_100002);
        }

        if(isSxOrder){
            OrderPaymentScaleDTO scaleDTO = new OrderPaymentScaleDTO();
            scaleDTO.setRefundAmount(orderPayRelationDTO.getRefundMoney().add(refundMoney));
            wrapper = new EntityWrapper<>();
            wrapper.eq("pay_relation_id", orderPayRelationDTO.getId());
            flag = orderPaymentScaleService.update(scaleDTO, wrapper);
            if(!flag){
                throw new ServiceException(CodeEnum.FAIL_100002);
            }
        }
    }

    /**
     * 修改退款完成
     * @param orderReturnCommodityDTO
     */
    private void updateRefundFinish(OrderReturnCommodityDTO orderReturnCommodityDTO){
        OrderReturnCommodityDTO newOrderReturnCommodityDTO = new OrderReturnCommodityDTO();
        newOrderReturnCommodityDTO.setRefundStatus(2);
        Wrapper wrapper = new EntityWrapper<>();
        wrapper.eq("id", orderReturnCommodityDTO.getId());
        wrapper.eq("refund_status", orderReturnCommodityDTO.getRefundStatus());
        boolean flag = this.update(newOrderReturnCommodityDTO, wrapper);
        if(!flag){
            throw new ServiceException(CodeEnum.FAIL_100002);
        }
    }

    private void updateCencalPay(OrderPayRelationDTO orderPayRelationDTO, BigDecimal refundMoney){
        this.updateCencalPay(orderPayRelationDTO, refundMoney, false);
    }

    /**
     * 取消支付
     * @param orderPayRelationDTO
     * @param refundMoney
     * @param isSxOrder 是否是赊销订单 true 是
     */
    private void updateCencalPay(OrderPayRelationDTO orderPayRelationDTO, BigDecimal refundMoney, boolean isSxOrder){
        OrderPayRelationDTO newOrderPayRelationDTO = new OrderPayRelationDTO();
        newOrderPayRelationDTO.setRefundMoney(orderPayRelationDTO.getRefundMoney().add(refundMoney));
        newOrderPayRelationDTO.setPayState(4);
        Wrapper wrapper = new EntityWrapper<>();
        wrapper.eq("id", orderPayRelationDTO.getId());
        wrapper.eq("pay_state", orderPayRelationDTO.getPayState());
        wrapper.and("{0} <= {1}", newOrderPayRelationDTO.getRefundMoney(), orderPayRelationDTO.getRealPayMoney());
        boolean flag = orderPayRelationService.update(newOrderPayRelationDTO, wrapper);
        if(!flag){
            throw new ServiceException(CodeEnum.FAIL_100002);
        }

        if(isSxOrder){
            OrderPaymentScaleDTO scaleDTO = new OrderPaymentScaleDTO();
            scaleDTO.setRefundAmount(orderPayRelationDTO.getRefundMoney().add(refundMoney));
            scaleDTO.setPaymentStatus(4);
            wrapper = new EntityWrapper<>();
            wrapper.eq("pay_relation_id", orderPayRelationDTO.getId());
            flag = orderPaymentScaleService.update(scaleDTO, wrapper);
            if(!flag){
                throw new ServiceException(CodeEnum.FAIL_100002);
            }
        }
    }


    /**
     * @Description: 卖家签收退货
     * @Author: WangChenYu
     * @Param: [dto]
     * @Date: 2020-10-16 17:41
     */
    @Transactional
    public boolean SellerSignForReturn(OrderReturnCommodityDTO dto) {
        OrderReturnCommodityDTO updateDto = new OrderReturnCommodityDTO();
        updateDto.setId(dto.getId());
        updateDto.setAfterSalesState(2);//2继续售后中
        updateDto.setShipState(2);//2卖家待发货
        updateDto.setIsRefund(0);//0不退款
        boolean update = this.updateById(updateDto);
        if (!update) {
            return false;
        }
        //增加买家发货倒计时
        Date expireTime = this.getExpireTime(OrderExpireTimeConstant.WAIT_DELIVER_GOODS);
        OrderReturnExpirationDateSaveBO expirationDateDTO = new OrderReturnExpirationDateSaveBO();
        expirationDateDTO.setOrderReturnId(dto.getId());//退换货表id
        expirationDateDTO.setStatus(2);//卖家家待发货
        expirationDateDTO.setShopType(1);//卖家
        expirationDateDTO.setExpirationTime(expireTime);
        orderReturnExpirationDateService.addCheck(expirationDateDTO);
        //发送消息
        this.sendMsg(dto.getBuyersShopId(), "售后订单签收", "卖家已签收，请等待卖家重新发货!", dto.getId(), 1);
        //保存订单售后日志
        OrderAfterSaleLogDTO logDTO = new OrderAfterSaleLogDTO();
        logDTO.setAfterState(5);
        logDTO.setOrderReturnCommodityId(dto.getId());//订单售后表id
        logDTO.setCreateUserId(dto.getSellerShopId());//卖家家店铺id
        logDTO.setProgressContent("卖家已签收，请等待卖家重新发货。");
        orderAfterSaleLogService.add(logDTO);
        //发送短信
        this.sendSms(dto.getBuyersShopId(), dto.getSellerShopId());
        return true;
    }

    /**
     * @Description: 买家签收
     * @Author: WangChenYu
     * @Param: [id]
     * @Date: 2020-10-09 14:58
     */
    @Transactional
    @Override
    public Result updateBuyersSignFo(Long id) {
        Result result = new Result<>();
        OrderReturnCommodityDTO dto = this.selectById(id);
        if (null == dto) {
            result.setCode(CodeEnum.AFTER_SALE_ORDER_ERROR_320001.getCode());
            result.setMsg(CodeEnum.AFTER_SALE_ORDER_ERROR_320001.getMsg());
            return result;
        }
        OrderReturnCommodityDTO updateDto = new OrderReturnCommodityDTO();
        //买家签收，售后完成
        updateDto.setId(dto.getId());
        updateDto.setAfterSalesState(3);//3售后完成
        updateDto.setShipState(5);//5买家已签收
        boolean update = this.updateById(updateDto);
        if (!update) {
            result.setCode(CodeEnum.AFTER_SALE_ORDER_ERROR_320000.getCode());
            result.setMsg(CodeEnum.AFTER_SALE_ORDER_ERROR_320000.getMsg());
            return result;
        }
        //更改订单状态已签收
        Boolean checkReturnOrder = this.checkReturnGoodsOrder(dto.getOrderId());
        if (checkReturnOrder) {
            // 获取订单商品数量,如果退款数量和商品数量相等改变订单状态
            OrderCommodityRelationDTO orderGoods = orderCommodityRelationService.selectById(dto.getOrderCommodityId());
            if (null != orderGoods) {
                if (orderGoods.getNum().equals(orderGoods.getReturnCommodityNum())) {
                    //更改订单状态为已签收
                    orderStatusService.saveOrderReceive(updateDto.getOrderId(), false);
                } else {
                    // 恢复订单倒计时
                    this.countdownToResumeOrder(dto.getOrderId(), dto.getCreateTime());
                }
            }
        } else {
            // 恢复订单倒计时
            this.countdownToResumeOrder(dto.getOrderId(), dto.getCreateTime());
        }
        //发送消息
        this.sendMsg(dto.getSellerShopId(), "售后订单", "买家已签收，售后完成!", dto.getId(), 2);
        //保存订单售后日志
        OrderAfterSaleLogDTO logDTO = new OrderAfterSaleLogDTO();
        logDTO.setAfterState(6);
        logDTO.setOrderReturnCommodityId(dto.getId());//订单售后表id
        logDTO.setCreateUserId(dto.getBuyersShopId());//卖家家店铺id
        logDTO.setProgressContent("买家已签收，服务完成。");
        orderAfterSaleLogService.add(logDTO);
        //发送短信
        this.sendSms(dto.getBuyersShopId(), dto.getSellerShopId());
        result.setCode(CodeEnum.SUCCESS.getCode());
        result.setMsg(CodeEnum.SUCCESS.getMsg());
        return result;
    }

    /**
     * @Description: 买家申请平台介入
     * @Author: WangChenYu
     * @Param: [id]
     * @Date: 2020-10-09 14:58
     */
    @Transactional
    @Override
    public Result<List<String>> updateInterventionState(Long id) {
        Result<List<String>> result = new Result<>();
        OrderReturnCommodityDTO dto = this.selectById(id);
        if (dto == null) {
            result.setCode(CodeEnum.AFTER_SALE_ORDER_ERROR_320001.getCode());
            result.setMsg(CodeEnum.AFTER_SALE_ORDER_ERROR_320001.getMsg());
            return result;
        }
        //判断是否已申请过
        if (dto.getInterventionState() != 0) {
            result.setCode(CodeEnum.AFTER_SALE_ORDER_ERROR_320002.getCode());
            result.setMsg(CodeEnum.AFTER_SALE_ORDER_ERROR_320002.getMsg());
            return result;
        }
        OrderReturnCommodityDTO updateDto = new OrderReturnCommodityDTO();
        updateDto.setId(dto.getId());
        updateDto.setInterventionState(1);//1平台介入中
        boolean update = this.updateById(updateDto);
        if (!update) {
            result.setCode(CodeEnum.AFTER_SALE_ORDER_ERROR_320000.getCode());
            result.setMsg(CodeEnum.AFTER_SALE_ORDER_ERROR_320000.getMsg());
            return result;
        }
        //发送消息
        this.sendMsg(dto.getBuyersShopId(), "售后订单", "您已申请平台介入，请等待结果!", dto.getId(), 1);
        //保存订单售后日志
        OrderAfterSaleLogDTO logDTO = new OrderAfterSaleLogDTO();
        logDTO.setAfterState(7);
        logDTO.setOrderReturnCommodityId(dto.getId());//订单售后表id
        logDTO.setCreateUserId(dto.getBuyersShopId());//卖家家店铺id
        logDTO.setProgressContent("买家已申请平台介入，请等待平台处理。");
        orderAfterSaleLogService.add(logDTO);
        //发送短信
        this.sendSms(dto.getBuyersShopId(), dto.getSellerShopId());
        result.setCode(CodeEnum.SUCCESS.getCode());
        result.setMsg(CodeEnum.SUCCESS.getMsg());
        return result;
    }

    /**
     * @Description: 平台处理
     * @Author: WangChenYu
     * @Param: [updateBO]
     * @Date: 2020-10-09 14:55
     */
    @Transactional
    @Override
    public Result<List<String>> updateInterventionDeal(OrderReturnCommodityUpdateBO updateBO) {
        Result<List<String>> result = new Result<>();
        OrderReturnCommodityDTO dto = this.selectById(updateBO.getId());
        if (dto == null) {
            result.setCode(CodeEnum.AFTER_SALE_ORDER_ERROR_320001.getCode());
            result.setMsg(CodeEnum.AFTER_SALE_ORDER_ERROR_320001.getMsg());
            return result;
        }
        if (dto.getInterventionState() > ONE) {
            result.setCode(CodeEnum.AFTER_SALE_ORDER_ERROR_320002.getCode());
            result.setMsg(CodeEnum.AFTER_SALE_ORDER_ERROR_320002.getMsg());
            return result;
        }
        OrderReturnCommodityDTO updateDto = new OrderReturnCommodityDTO();
        updateDto.setId(dto.getId());
        updateDto.setInterventionState(updateBO.getInterventionState());//平台操作
        if (StringUtils.isNotBlank(updateBO.getPlatformRemarks())) {
            updateDto.setPlatformRemarks(updateBO.getPlatformRemarks());//平台备注
        }
        boolean update = this.updateById(updateDto);
        if (!update) {
            result.setCode(CodeEnum.AFTER_SALE_ORDER_ERROR_320000.getCode());
            result.setMsg(CodeEnum.AFTER_SALE_ORDER_ERROR_320000.getMsg());
            return result;
        }
        //保存订单售后日志
        OrderAfterSaleLogDTO logDTO = new OrderAfterSaleLogDTO();
        logDTO.setAfterState(EIGHT);
        logDTO.setOrderReturnCommodityId(dto.getId());
        logDTO.setCreateUserId(updateBO.getSysUserId());
        if (updateBO.getInterventionState() == ONE) {
            logDTO.setProgressContent("平台已介入，请等待。");
        } else if (updateBO.getInterventionState() == TWO) {
            logDTO.setProgressContent("平台协调处理中。");
        } else if (updateBO.getInterventionState() == THREE) {
            logDTO.setProgressContent("平台判定买家赢，等待卖家处理。");
        } else if (updateBO.getInterventionState() == FOUR) {
            logDTO.setProgressContent("平台判断卖家赢，等待买家处理。");
        }
        orderAfterSaleLogService.add(logDTO);
        //发送短信
        this.sendSms(dto.getBuyersShopId(), dto.getSellerShopId());
        result.setCode(CodeEnum.SUCCESS.getCode());
        result.setMsg(CodeEnum.SUCCESS.getMsg());
        return result;
    }

    /**
     * @Description: 平台判定后，买家卖家同意与否操作
     * @Author: WangChenYu
     * @Param: [id, isState1同意，2不同意, type:0买家,1卖家]
     * @Date: 2020-10-09 14:58
     */
    @Override
    public Result<List<String>> updateIsState(Long id, Integer isState, Integer type) {
        if (type == 1) {
            return this.involvedSellerOperating(id, isState);
        } else {
            return this.involvedBuyerOperating(id, isState);
        }
    }

    /**
     * @Description: 个人中心我的售后列表
     * @Author: WangChenYu
     * @Param: [bo]
     * @Date: 2020-10-09 14:59
     */
    @Override
    public Page<OrderReturnCommodityListVO> queryPageList(OrderReturnCommodityListBO bo) {
        Page<OrderReturnCommodityListVO> page = new Page<>(bo.getPageNo(), bo.getPageSize());
        List<OrderReturnCommodityListVO> list = baseMapper.queryPageList(page, bo);
        page.setRecords(list);
        return page;
    }

    /**
     * @Description: 查询售后订单退换货详情
     * @Author: WangChenYu
     * @Param: [id]
     * @Date: 2020-10-09 14:59
     */
    @Override
    public OrderReturnCommodityDetailsVO getDetailsById(Long id) {
        OrderReturnCommodityDetailsVO detailsById = baseMapper.getDetailsById(id);
        if (detailsById == null) {
            return null;
        }
        List<OrderAfterSaleLogMsgVO> logMsgList = baseMapper.queryAfterOrderLog(detailsById.getId());
        if (!isNull(logMsgList)) {
            detailsById.setLogList(logMsgList);
        }
        // 获取商品名称
        OrderCommodityRelationDTO selectById = orderCommodityRelationService.selectById(detailsById.getOrderCommodityId());
        if (selectById != null && CustomizeUtil.strIsNotNull(selectById.getCommodityName())) {
            detailsById.setGoodsName(selectById.getCommodityName());
        }

        List<OrderAfterShipDTO> shipList = orderAfterShipService.getListByOrderId(id);
        detailsById.setShipList(shipList);
        return detailsById;
    }

    /**
     * @Description: 后台管理系统售后订单列表
     * @Author: WangChenYu
     * @Param: [bo]
     * @Date: 2020-10-09 15:00
     */
    @Override
    public Page<OrderReturnCommodityAdminListVO> queryAdminPageList(OrderReturnCommodityAdminBO bo) {
        Page<OrderReturnCommodityAdminListVO> page = new Page<>(bo.getPageNo(), bo.getPageSize());
        List<OrderReturnCommodityAdminListVO> list = baseMapper.queryAdminPageList(page, bo);
        page.setRecords(list);
        return page;
    }

    /**
     * @Description: 统计售后订单及投诉与建议未处理数量
     * @Author: WangChenYu
     * @Param: []
     * @Date: 2020-10-09 15:00
     */
    @Override
    public Integer getAfterOrderNumber() {
        Integer afterSaleNumber = baseMapper.getAfterSaleNumber();
        Integer complaintsNumber = baseMapper.getComplaintsNumber();
        return afterSaleNumber + complaintsNumber;
    }

    @Override
    public Result<List<String>> updateConsortState(Long id, Integer state, String context) {
        log.info("售后订单id : {},状态 : {},平台协调内容 : {}", id, state, context);
        Result<List<String>> result = new Result<>();
        OrderReturnCommodityDTO dto = this.selectById(id);
        if (null == dto) {
            result.setCode(CodeEnum.AFTER_SALE_ORDER_ERROR_320001.getCode());
            result.setMsg(CodeEnum.AFTER_SALE_ORDER_ERROR_320001.getMsg());
            return result;
        }
        if (state == 1) {
            if (dto.getType() == 1) {
                // 换货
                boolean backGoods = this.buyersWinBackGoods(dto, context);
                if (!backGoods) {
                    result.setCode(CodeEnum.AFTER_SALE_ORDER_ERROR_320000.getCode());
                    result.setMsg(CodeEnum.AFTER_SALE_ORDER_ERROR_320000.getMsg());
                    return result;
                }
                result.setCode(CodeEnum.SUCCESS.getCode());
                result.setMsg(CodeEnum.SUCCESS.getMsg());
                return result;
            } else {
                // 退货
                //买赢,订单取消,退回货款,售后完成
                boolean buyersWin = this.consortBuyersWin(dto, context);
                if (!buyersWin) {
                    result.setCode(CodeEnum.AFTER_SALE_ORDER_ERROR_320000.getCode());
                    result.setMsg(CodeEnum.AFTER_SALE_ORDER_ERROR_320000.getMsg());
                    return result;
                }
                result.setCode(CodeEnum.SUCCESS.getCode());
                result.setMsg(CodeEnum.SUCCESS.getMsg());
                return result;
            }
        } else {
            //卖赢,订单完成,解冻货款,售后完成
            boolean sellerWin = this.consortSellerWin(dto, context);
            if (!sellerWin) {
                //订单签收
                commonService.saveReceive(dto.getOrderId(), false);
                result.setCode(CodeEnum.AFTER_SALE_ORDER_ERROR_320000.getCode());
                result.setMsg(CodeEnum.AFTER_SALE_ORDER_ERROR_320000.getMsg());
                return result;
            }
            result.setCode(CodeEnum.SUCCESS.getCode());
            result.setMsg(CodeEnum.SUCCESS.getMsg());
            return result;
        }
    }

    /**
     * @Description: 平台协调买家赢退换货
     * @Author: chenyu.wang
     * @Params: [dto, context]
     * @Date: 2020.11.05 14:15
     */
    public boolean buyersWinBackGoods(OrderReturnCommodityDTO dto, String context) {
        OrderReturnCommodityDTO returnCommodityDTO = new OrderReturnCommodityDTO();
        returnCommodityDTO.setId(dto.getId());
        returnCommodityDTO.setAfterSalesState(2);
       // returnCommodityDTO.setShipState(1);
        returnCommodityDTO.setIsRefund(0);
        returnCommodityDTO.setConsortState(1);
        if (StringUtils.isNotBlank(context)) {
            returnCommodityDTO.setConsortRemarks(context);
        }
        boolean update = this.updateById(returnCommodityDTO);
        if (!update) {
            return false;
        }
        //发送短信
        this.sendSms(dto.getBuyersShopId(), dto.getSellerShopId());
        return true;
    }

    /**
     * @Description: 平台协调买家赢退款
     * @Author: WangChenYu
     * @Param: [dto, context]
     * @Date: 2020-10-12 10:27
     */
    @Transactional
    public boolean consortBuyersWin(OrderReturnCommodityDTO dto, String context) {
        OrderReturnCommodityDTO updateDTO = new OrderReturnCommodityDTO();
        updateDTO.setId(dto.getId());
        updateDTO.setConsortState(1);
        updateDTO.setAfterSalesState(2);
            //updateDTO.setShipState(1);

        //买赢,订单取消,退回货款,售后完成

        if (StringUtils.isNotBlank(context)) {
            updateDTO.setConsortRemarks(context);
        }
        boolean update = this.updateById(updateDTO);
        if (!update) {
            return false;
        }
        //发送短信
        this.sendSms(dto.getBuyersShopId(), dto.getSellerShopId());
        return true;
    }

    /**
     * @Description: 平台协调卖家赢
     * @Author: WangChenYu
     * @Param: [dto, context]
     * @Date: 2020-10-12 10:38
     */
    @Transactional
    public boolean consortSellerWin(OrderReturnCommodityDTO dto, String context) {
        //卖赢,订单完成,解冻货款,售后完成
        OrderReturnCommodityDTO updateDTO = new OrderReturnCommodityDTO();
        updateDTO.setId(dto.getId());
        updateDTO.setAfterSalesState(2);
        updateDTO.setConsortState(2);
        if (StringUtils.isNotBlank(context)) {
            updateDTO.setConsortRemarks(context);
        }
        boolean update = this.updateById(updateDTO);
        if (!update) {
            return false;
        }

        //发送短信
        this.sendSms(dto.getBuyersShopId(), dto.getSellerShopId());
        return true;
    }

    /**
     * @Description: 发送站内信
     * @Author: WangChenYu
     * @Param: [shopId, title, content, orderId, shopType]
     * @Date: 2020-10-09 15:01
     */
    @Async
    public void sendMsg(Long shopId, String title, String content, Long orderId, Integer shopType) {
        try {
            ResponseDTO responseDTO = new ResponseDTO();
            responseDTO.setMessageId(shopId + "");
            MessageAnnouncementSaveBO messageAnnouncementSaveBO = new MessageAnnouncementSaveBO();
            messageAnnouncementSaveBO.setType(MessageEnum.SYS_MESSAGE.getCode());
            messageAnnouncementSaveBO.setShopId(shopId);
            messageAnnouncementSaveBO.setTitle(title);
            messageAnnouncementSaveBO.setContent(content);
            messageAnnouncementSaveBO.setTextType(1);
            messageAnnouncementSaveBO.setJumpType(MessageEnum.AFTER_SALE_ORDER.getCode() + "");
            if (shopType == 1) {//买家
                messageAnnouncementSaveBO.setShopType(MessageEnum.SHOP_TYPE_1.getCode());
            } else {//卖家
                messageAnnouncementSaveBO.setShopType(MessageEnum.SHOP_TYPE_2.getCode());
            }
            messageAnnouncementSaveBO.setKey(orderId + "");
            responseDTO.setData(messageAnnouncementSaveBO);
            iKafkaProducerService.senMessage(JSON.toJSONString(responseDTO), MessageTopicType.COMMENT_MESSAGE_TOPIC);
        } catch (Exception e) {
            log.error("售后发送站内信错误信息:{}", e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * @description:检查同一订单是否存在未完成的退款售后
     * @author: chenyu.wang
     * @date: 2020-08-26
     */
    private Boolean checkReturnOrder(Long orderId) {
        List<OrderReturnCommodityDTO> realList = new ArrayList<>();
        Wrapper<OrderReturnCommodityDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("order_id", orderId);
        wrapper.eq("type", ZERO);
        List<OrderReturnCommodityDTO> list = this.selectList(wrapper);
        if (isNull(list)) {
            return true;
        }
        for (OrderReturnCommodityDTO dto : list) {
            if (dto.getAfterSalesState() != THREE) {
                realList.add(dto);
            }
        }
        return isNull(realList);
    }

    /**
     * @Description: 检查同一订单是否存在未完成的换货售后
     * @Author: chenyu.wang
     * @Params: [orderId]
     * @Date: 2020.11.05 14:55
     */
    private Boolean checkReturnGoodsOrder(Long orderId) {
        List<OrderReturnCommodityDTO> realList = new ArrayList<>();
        Wrapper<OrderReturnCommodityDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("order_id", orderId);
        wrapper.eq("type", 1);
        List<OrderReturnCommodityDTO> list = this.selectList(wrapper);
        if (isNull(list)) {
            return true;
        }
        for (OrderReturnCommodityDTO dto : list) {
            if (dto.getAfterSalesState() != THREE) {
                realList.add(dto);
            }
        }
        return isNull(realList);
    }

    /**
     * @description:平台介入判定后卖家操作
     * @author: chenyu.wang
     * @date: 2020-09-02
     */
    private Result<List<String>> involvedSellerOperating(Long id, Integer state) {
        Result<List<String>> result = new Result<>();
        OrderReturnCommodityDTO dto = this.selectById(id);
        if (null == dto) {
            result.setCode(CodeEnum.AFTER_SALE_ORDER_ERROR_320001.getCode());
            result.setMsg(CodeEnum.AFTER_SALE_ORDER_ERROR_320001.getMsg());
            return result;
        }
        //判断是否重复点击
        if (dto.getSellerState() == 1 || dto.getSellerState() == 2) {
            result.setCode(CodeEnum.AFTER_SALE_ORDER_ERROR_320002.getCode());
            result.setMsg(CodeEnum.AFTER_SALE_ORDER_ERROR_320002.getMsg());
            return result;
        }
        OrderReturnCommodityDTO updateDto = new OrderReturnCommodityDTO();
        updateDto.setId(dto.getId());
        updateDto.setSellerState(state);
        if (dto.getType()!=2){
            if (state == 1) {
                updateDto.setShipState(1);
            }
        }
        boolean update = this.updateById(updateDto);
        if (!update) {
            result.setCode(CodeEnum.AFTER_SALE_ORDER_ERROR_320000.getCode());
            result.setMsg(CodeEnum.AFTER_SALE_ORDER_ERROR_320000.getMsg());
            return result;
        }
        //发送消息
        String content;
        if (state == 1) {
            content = "卖家已同意!";
            if (dto.getType()!=2){
                //增加卖家发货倒计时
                Date expireTime = this.getExpireTime(OrderExpireTimeConstant.WAIT_DELIVER_GOODS);
                OrderReturnExpirationDateSaveBO expirationDateDTO = new OrderReturnExpirationDateSaveBO();
                expirationDateDTO.setOrderReturnId(dto.getId());//退换货表id
                expirationDateDTO.setStatus(1);//买家待发货
                expirationDateDTO.setShopType(0);//买家
                expirationDateDTO.setExpirationTime(expireTime);
                orderReturnExpirationDateService.addCheck(expirationDateDTO);
            }
        } else {
            content = "卖家未同意!";
        }
        this.sendMsg(dto.getBuyersShopId(), "售后订单", content, dto.getId(), 1);
        //保存订单售后日志
        OrderAfterSaleLogDTO logDTO = new OrderAfterSaleLogDTO();
        logDTO.setAfterState(NINE);
        logDTO.setOrderReturnCommodityId(dto.getId());
        logDTO.setCreateUserId(dto.getSellerShopId());
        logDTO.setProgressContent("服务单平台介入后" + content);
        orderAfterSaleLogService.add(logDTO);
        //发送短信
        this.sendSms(dto.getBuyersShopId(), dto.getSellerShopId());
        result.setCode(CodeEnum.SUCCESS.getCode());
        result.setMsg(CodeEnum.SUCCESS.getMsg());
        return result;
    }

    /**
     * @description:平台介入判定后买家家操作
     * @author: chenyu.wang
     * @date: 2020-09-02
     */
    private Result<List<String>> involvedBuyerOperating(Long id, Integer state) {
        Result<List<String>> result = new Result<>();
        OrderReturnCommodityDTO dto = this.selectById(id);
        if (null == dto) {
            result.setCode(CodeEnum.AFTER_SALE_ORDER_ERROR_320001.getCode());
            result.setMsg(CodeEnum.AFTER_SALE_ORDER_ERROR_320001.getMsg());
            return result;
        }
        //判断是否重复点击
        if (dto.getBuyersState() == 1 || dto.getBuyersState() == 2) {
            result.setCode(CodeEnum.AFTER_SALE_ORDER_ERROR_320002.getCode());
            result.setMsg(CodeEnum.AFTER_SALE_ORDER_ERROR_320002.getMsg());
            return result;
        }
        //买家操作
        OrderReturnCommodityDTO updateDto = new OrderReturnCommodityDTO();
        updateDto.setId(dto.getId());
        updateDto.setBuyersState(state);
        if (state == 1) {//平台判定后买家同意，售后订单状态为已完成，否则订单挂起
            updateDto.setAfterSalesState(3);
        }
        boolean update = this.updateById(updateDto);
        if (!update) {
            result.setCode(CodeEnum.AFTER_SALE_ORDER_ERROR_320000.getCode());
            result.setMsg(CodeEnum.AFTER_SALE_ORDER_ERROR_320000.getMsg());
            return result;
        }
        //发送消息
        String content;
        if (state == 1) {
            content = "买家已同意!";
        } else {
            content = "买家未同意!";
        }
        this.sendMsg(dto.getSellerShopId(), "售后订单", content, dto.getId(), 2);
        //保存订单售后日志
        OrderAfterSaleLogDTO logDTO = new OrderAfterSaleLogDTO();
        logDTO.setAfterState(TEN);
        logDTO.setOrderReturnCommodityId(dto.getId());
        logDTO.setCreateUserId(dto.getBuyersShopId());
        logDTO.setProgressContent("服务单平台介入后" + content);
        orderAfterSaleLogService.add(logDTO);
        //发送短信
        this.sendSms(dto.getBuyersShopId(), dto.getSellerShopId());
        result.setCode(CodeEnum.SUCCESS.getCode());
        result.setMsg(CodeEnum.SUCCESS.getMsg());
        return result;
    }

    /**
     * @description:发送短信
     * @author: chenyu.wang
     * @date: 2020-09-16
     * @return:
     */
    @Async
    public void sendSms(Long buyerShopId, Long sellerShopId) {
        List<Long> idList = new ArrayList<>();
        idList.add(buyerShopId);
        idList.add(sellerShopId);
        //获取店铺手机号
        List<ShopInfoVO> users = shopInfoService.getByShopIds(idList);
        if (!isNull(users)) {
            SmsInfoSaveBO smsInfoSaveBO;
            for (ShopInfoVO user : users) {
                try {
                    smsInfoSaveBO = new SmsInfoSaveBO();
                    smsInfoSaveBO.setMobile(user.getMobile());
                    //发送短信
                    smsInfoService.saveAfterSale(smsInfoSaveBO);
                } catch (Exception e) {
                    log.error("售后发送短信失败!");
                    e.printStackTrace();
                }
            }
        } else {
            log.info("暂未查询到店铺手机号,发送短信失败!");
        }
    }

    /**
     * @Description: 获取过期时间
     * @Author: WangChenYu
     * @Param: [dictName]
     * @Date: 2020-10-12 16:14
     */
    private Date getExpireTime(String dictName) {
        SysDictDTO sysDictDTO = sysDictService.getByName(dictName);
        String time = sysDictDTO.getValue();
        //当前时间
        Date currentDateTime = DateUtils.getCurrentDateTime();
        return DateUtils.addDay(currentDateTime, Integer.parseInt(time));
    }

    /**
     * 根据店铺id获和类型取售后中或者申请售后的数量
     *
     * @param buyerShopId
     * @return
     */
    @Override
    public Integer getMyAfterSalesNum(Long buyerShopId, Integer type) {
        Wrapper wrapper = new EntityWrapper();
        if (type == 1) {
            wrapper.eq("buyers_shop_id", buyerShopId);
            wrapper.eq("is_buyer_look", 0);
        } else {
            wrapper.eq("seller_shop_id", buyerShopId);
            wrapper.eq("is_seller_look", 0);
        }

        wrapper.in("after_sales_state", Arrays.asList(new Integer[]{1, 2}));
        return selectCount(wrapper);
    }

    @Override
    public Result updateOrderAfterSale(OrderAfterSaleUpdateBO updateBo) {
        Result<Object> result = new Result<>();
        Long id = updateBo.getId();
        OrderReturnCommodityDTO dto = this.selectById(id);
        if (null == dto) {
            result.setCode(CodeEnum.AFTER_SALE_ORDER_ERROR_320001.getCode());
            result.setMsg(CodeEnum.AFTER_SALE_ORDER_ERROR_320001.getMsg());
            return result;
        }
        if (dto.getAfterSalesAuditState() != 1) {
            result.setCode(CodeEnum.AFTER_SALE_ORDER_ERROR_320004.getCode());
            result.setMsg(CodeEnum.AFTER_SALE_ORDER_ERROR_320004.getMsg());
            return result;
        }
        OrderReturnCommodityDTO updateDto = new OrderReturnCommodityDTO();
        updateDto.setType(updateBo.getType());
        if (updateBo.getType() == 0 || updateBo.getType() == 2) {
            updateDto.setIsRefund(1);
            if(updateBo.getType() != 2){
                updateDto.setSubNumber(updateBo.getSubNumber());
            }
        } else {
            updateDto.setIsRefund(0);
            updateDto.setSubNumber(updateBo.getSubNumber());
        }

        updateDto.setReturnReason(updateBo.getReturnReason());
        updateDto.setProblemDescription(updateBo.getProblemDescription());
        updateDto.setCertificateFile(updateBo.getCertificateFile());
        updateDto.setContactUser(updateBo.getContactUser());
        updateDto.setContactPhone(updateBo.getContactPhone());
        updateDto.setAfterSalesState(1);
        updateDto.setAfterSalesAuditState(1);
        updateDto.setInterventionState(0);
        updateDto.setOrderId(dto.getOrderId());
        //计算退款金额
        OrderCommodityRelationDTO orderCommodityRelationDTO = orderCommodityRelationService.selectById(dto.getOrderCommodityId());
//        //单价
//        BigDecimal onePrice = orderCommodityRelationDTO.getActualMoney().divide(new BigDecimal(orderCommodityRelationDTO.getNum()), 4, BigDecimal.ROUND_HALF_UP);
//        if(updateBo.getType()==2){
//            updateDto.setRefundPrice(updateBo.getReturnMoney());
//        }else {
//            updateDto.setRefundPrice(onePrice.multiply(new BigDecimal(updateBo.getSubNumber())));
//        }

        Result rs = saveRefundMoney(updateDto, updateBo.getType(), updateBo.getSubNumber(), updateBo.getReturnMoney(), orderCommodityRelationDTO);
        if(!rs.success()){
            return rs;
        }
        updateDto.setId(id);
        boolean update = this.updateById(updateDto);
        if (!update) {
            result.setCode(CodeEnum.FAIL_100008.getCode());
            result.setMsg(CodeEnum.FAIL_100008.getMsg());
            return result;
        }
        result.setCode(CodeEnum.SUCCESS.getCode());
        result.setMsg(CodeEnum.SUCCESS.getMsg());
        return result;
    }



    @Override
    public OrderUpdateAfterSaleDetailsVO getUpdateOrderAfterSaleById(Long id) {
        // 查询售后信息
        OrderReturnCommodityDTO orderReturnCommodity = this.selectById(id);
        log.info("修改售后,查询售后信息 : {}", orderReturnCommodity);
        if (null == orderReturnCommodity) {
            return null;
        }
        // 查询订单商品信息
        OrderCommodityRelationDTO orderCommodityRelation = orderCommodityRelationService.selectById(orderReturnCommodity.getOrderCommodityId());
        // 查询商品图片
        CommodityInfoDTO commodityInfo = commodityInfoService.selectById(orderCommodityRelation.getCommodityId());
        OrderUpdateAfterSaleDetailsVO vo = new OrderUpdateAfterSaleDetailsVO();
        vo.setOrderReturnCommodity(orderReturnCommodity);
        vo.setOrderCommodityRelation(orderCommodityRelation);
        if (null != commodityInfo) {
            if (StringUtils.isNotBlank(commodityInfo.getLogoUrl())) {
                vo.setGoodsImg(commodityInfo.getLogoUrl());
            }
        }
        return vo;
    }

    @Override
    public Integer afterSalesQuantityToBeProcessed(Long shopId) {
        Wrapper<OrderReturnCommodityDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("seller_shop_id", shopId)
                .andNew()
                .eq("after_sales_state", 1)
                .or()
                .eq("after_sales_state", 2);
        List<OrderReturnCommodityDTO> selectList = this.selectList(wrapper);
        return selectList.size();
    }

    @Override
    public boolean checkWhetherTheOrderHasAfterSales(Long orderId) {
        // 获取订单商品
        Wrapper<OrderCommodityRelationDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("order_id", orderId);
        List<OrderCommodityRelationDTO> list = orderCommodityRelationService.selectList(wrapper);
        for (OrderCommodityRelationDTO orderCommodityRelationDTO : list) {
            // 查询是否有售后
            Wrapper<OrderReturnCommodityDTO> returnCommodityDTOWrapper = new EntityWrapper<>();
            returnCommodityDTOWrapper.eq("order_commodity_id", orderCommodityRelationDTO.getId());
            OrderReturnCommodityDTO one = this.selectOne(returnCommodityDTOWrapper);
            if (one != null) {
                return false;
            }
        }
        return true;
    }

    /**
     * @return : void
     * @Author :chenyu.wang
     * @Description : 暂停订单倒计时
     * @Date : 2021.03.25 14:10
     * @Param : [orderId, state:0恢复,1暂停]
     **/
    private void pauseOrderCountdown(Long orderId) {
        // 获取待签收状态的订单倒计时
        Wrapper<OrderExpirationDateDTO> a = new EntityWrapper<>();
        a.eq("order_id", orderId)
                .eq("status", 4);
        OrderExpirationDateDTO dto = orderExpirationDateService.selectOne(a);
        if (dto == null) {
            return;
        }
        OrderExpirationDateDTO updateDto = new OrderExpirationDateDTO();
        updateDto.setId(dto.getId());
        updateDto.setIsFlag(1);
        orderExpirationDateService.updateById(updateDto);
    }

    /**
     * @return : void
     * @Author :chenyu.wang
     * @Description : 恢复订单倒计时
     * @Date : 2021.03.25 14:35
     * @Param : [orderId, startTime]
     **/
    private void countdownToResumeOrder(Long orderId, Date startTime) {
        // 获取待签收状态的订单倒计时
        Wrapper<OrderExpirationDateDTO> a = new EntityWrapper<>();
        a.eq("order_id", orderId)
                .eq("status", 4);
        OrderExpirationDateDTO dto = orderExpirationDateService.selectOne(a);
        if (dto == null) {
            return;
        }
        try {
            Date endDate = new Date();
            // 时间差额 = 售后接受时间 - 售后开始时间
            int minute = (int) ((endDate.getTime() - startTime.getTime()) / (1000 * 60));
            // 新的倒计时 = 原来的倒计时 + 差额分钟
            Calendar cal = Calendar.getInstance();
            cal.setTime(dto.getExpirationTime());
            cal.add(Calendar.MINUTE, minute);
            // 新的过期时间
            Date newExpirationTime = cal.getTime();
            OrderExpirationDateDTO updateDto = new OrderExpirationDateDTO();
            updateDto.setId(dto.getId());
            updateDto.setExpirationTime(newExpirationTime);
            updateDto.setIsFlag(0);
            orderExpirationDateService.updateById(updateDto);
        } catch (Exception e) {
            log.error("恢复订单倒计时错误信息:{}", e.getMessage());
            e.printStackTrace();
        }
    }

}
